package com.spdd.mt.task;

import com.spdd.mt.biz.config.ConfigBean;
import com.spdd.mt.biz.entity.MtRechargeOrderEntity;
import com.spdd.mt.biz.manager.feishu.FeiShuService;
import com.spdd.mt.biz.manager.service.NotifyService;
import com.spdd.mt.biz.service.MtRechargeOrderService;
import com.spdd.mt.common.util.DateUtils;
import com.spdd.mt.config.ScheduledCondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 补偿回调通知任务
 *
 * @since 2025年04月06日
 */
@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class CompensateNotifyTask {

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private MtRechargeOrderService orderService;

    @Autowired
    private FeiShuService feiShuService;

    /**
     * 每隔5分钟执行一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void autoNotifyDy() {
        log.info("开始执行补偿回调任务");
        try {
            String month = DateUtils.getCurrentMonth();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String lastTime = fiveMinutesAgo.format(formatter);
            List<MtRechargeOrderEntity> list = orderService.getNeedNotify(month, lastTime, configBean.getMaxNotifyTimes());

            // 自动补偿要看一下上个月数据
            List<MtRechargeOrderEntity> lastList = orderService.getNeedNotify(DateUtils.getLastMonth(), lastTime, configBean.getMaxNotifyTimes());
            list.addAll(lastList);
            log.info("待补偿的数据量:{}", list.size());
            list.forEach(record -> notifyService.notifyMtOrder(record, 1));
        } catch (BadSqlGrammarException e) {
            log.info("语法错误异常, {}", e.getCause().getMessage());
        } catch (Exception e) {
            feiShuService.sendExceptionMsg(e);
            log.info("执行补偿回调任务异常", e);
        }
        log.info("执行补偿回调任务务结束");
    }

}
